<script lang="ts" setup>
import type { StaffItem } from '../data';

import { computed, ref, watch } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createStaff, updateStaff } from '#/api/system/staff';

import { useFormSchema } from '../data';

interface Props {
  staffData?: null | StaffItem;
}

defineOptions({
  name: 'StaffForm',
});

const props = withDefaults(defineProps<Props>(), {
  staffData: null,
});

const emit = defineEmits<{
  success: [];
}>();

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: handleConfirm,
});

const isUpdate = computed(() => !!props.staffData?.id);

const drawerTitle = computed(() => {
  return isUpdate.value ? '编辑职员' : '新增职员';
});

async function handleConfirm() {
  const { valid, values } = await formApi.submitForm();
  if (!valid) {
    return;
  }

  const hideLoading = message.loading({
    content: isUpdate.value ? '正在更新职员...' : '正在创建职员...',
    duration: 0,
    key: 'action_process_msg',
  });

  try {
    if (isUpdate.value && props.staffData?.id) {
      await updateStaff(props.staffData.id, values);
      message.success({
        content: '职员更新成功',
        key: 'action_process_msg',
      });
    } else {
      await createStaff(values);
      message.success({
        content: '职员创建成功',
        key: 'action_process_msg',
      });
    }
    drawerApi.close();
    emit('success');
  } catch {
    hideLoading();
  }
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: useFormSchema(),
  showDefaultActions: false,
});

const formData = ref<Partial<StaffItem>>({});

// 监听 props 变化，更新表单数据
watch(
  () => props.staffData,
  (newData) => {
    if (newData) {
      formData.value = { ...newData };
      formApi.setValues(newData);
    } else {
      formData.value = {};
      formApi.resetForm();
    }
  },
  { immediate: true },
);
</script>

<template>
  <Drawer
    :loading="false"
    :title="drawerTitle"
    class="w-[600px]"
    @cancel="drawerApi.close"
  >
    <Form />
  </Drawer>
</template>